/**
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Company: ---Technology Co. Ltd</p>
 * <p>2014-4-30</p>
 * @author Jan.Zhang
 */
package com.xianl.busiplat.service.impl;

import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.xianl.busiplat.dwz.Page;
import com.xianl.busiplat.exception.ExistedException;
import com.xianl.busiplat.po.User;
import com.xianl.busiplat.service.UserService;
import com.xianl.busiplat.shiro.ShiroDbRealm;
import com.xianl.busiplat.shiro.ShiroDbRealm.HashPassword;


/** 
 * desc:
 * <p>author: Jan.Zhang </p>
 * date: 2014-4-30
 */
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
	
	@Autowired
	private ShiroDbRealm shiroDbRealm;
	
	/* 
	 * desc:
	 * @see com.umpay.sc.plat.core.service.UserService#get(java.lang.String)
	 */
	@Override
	public User get(String username) {
		User user = new User();
		user.setUsername(username);
		return mapper.selectOne(user);
	}
	
	/* 
	 * desc:
	 * @see com.umpay.sc.plat.core.service.UserService#get(int)
	 */
	@Override
	public User get(int id) {
		User user = new User();
		user.setId(id);
		return mapper.selectOne(user);
	}

	/* 
	 * desc:
	 * @see com.umpay.sc.plat.core.service.UserService#find(com.umpay.sc.plat.core.dwz.Page, java.util.Map)
	 */
	@Override
	public List<User> find(Page page, Map<String, Object> params) {
		return mapper.findPage(page, params);
	}
	
	/* 
	 * desc:
	 * @see com.umpay.sc.plat.core.service.impl.BaseServiceImpl#save(java.lang.Object)
	 */
	@Override
	public void save(User entity) {
		if (mapper.selectOne(entity)!= null) {
			throw new ExistedException("用户添加失败，登录名：" + entity.getUsername() + "已存在。");
		}
		
//		if (userDao.findByRealname(user.getRealname()) != null) {
//			throw new ExistedException("用户添加失败，真实名：" + user.getRealname() + "已存在。");
//		}
		System.out.println(shiroDbRealm == null);
		//设定安全的密码，使用passwordService提供的salt并经过1024次 sha-1 hash
		if (StringUtils.isNotBlank(entity.getPlainPassword()) && shiroDbRealm != null) {
			HashPassword hashPassword = shiroDbRealm.encrypt(entity.getPlainPassword());
			entity.setSalt(hashPassword.salt);
			entity.setPassword(hashPassword.password);
		}
		System.out.println(entity.getPassword());
		mapper.insert(entity);
		shiroDbRealm.clearCachedAuthorizationInfo(entity.getUsername());
	}

	/* 
	 * desc:
	 * @see com.umpay.sc.plat.core.service.UserService#delete(int)
	 */
	@Override
	public void delete(Integer id) {
		User user = new User();
		user.setId(id);
		this.delete(user);
	}
	
}
